<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use App\Models\Article;
use DB;

class ArticleController extends Controller
{
    # 模型实例
	private $article;

	// 初始化
	public function __construct()
	{
		$this->article = new Article;
	}

    // 文章列表
	public function article_list(Request $request)
	{
	    # 获取页码
        $page = $request->input('page','1');
		# 标签数据
		$tags = DB::table('tags')->select('tid','tname')->get();
		# 文章列表
        $field_arr = ['title','article.aid','path','created_at','author','sort','click','is_show'];
        # $article = $this->article->getPageData('all','all','all',$field_arr);
        if(Cache::has('articles'.$page)){
            $article = Cache::get('articles'.$page);
        } else {
            $article = $this->article->getPageData('all','all','all',$field_arr);
            Cache::put('articles'.$page,$article,3600*24);
        }
		return view('admin/article_list',['tags'=>$tags,'articles'=>$article]);
	}
	
	// 添加文章
	public function article_add(Request $request)
	{
		$category = DB::table('category')->select('cname','cid')->get();
		if($request->isMethod('post')){
			$result = $this->validate($request,[
				'title' => 'required',
				'cid' => 'required|numeric',
				'content' => 'required',
				'keywords' => 'required',
				'description' => 'required',
			],[
				'title' => '请输入标题',
				'cid' => '请选择分类',
				'content' => '请输入文章内容',
				'keywords' => '请输入关键字',
				'description' => '请输入描述',
			]);

			// 接收数据
			$this->article->title = $request->input('title','','htmlspecialchars');
			$this->article->cid = $request->input('cid');
			$this->article->author = $request->input('author','','htmlspecialchars');
			$this->article->keywords = $request->input('keywords','','htmlspecialchars');
			$this->article->sort = $request->input('sort');
			$this->article->click = $request->input('click');
			$this->article->description = $request->input('description','','htmlspecialchars');
			$this->article->content = $request->input('content','内容为空','htmlspecialchars');
			
			$res = $this->article->save();
			if($res){
				$resu = $this->article->add_article_pic($request->input('content','内容为空','htmlspecialchars'));
				if($resu){
				    Cache::flush();
				    return redirect('/admin/article_list');
                } else {
				    return redirect('/prompt')->with(['message'=>'添加失败','url' =>'/admin/article_add', 'jumpTime'=>3,'status'=>'error']);
                }
			} else {
				return redirect('/prompt')->with(['message'=>'添加失败','url' =>'/admin/article_add', 'jumpTime'=>3,'status'=>'error']);
			}
			
		}
		return view('admin/article_add',['category'=>$category]);
	}

    // 修改文章
    public  function article_edit(Request $request,$aid)
    {
        # 查询分类
        $category = DB::table('category')->select('cname','cid')->get();
        # 查询文章信息
        $article = $this->article->find($aid);
        $cat = $article->category;
        # 更新文章
        if($request->isMethod('post')){
            $result = $this->validate($request,[
                'title' => 'required',
                'cid' => 'required|numeric',
                'content' => 'required',
                'keywords' => 'required',
                'description' => 'required',
            ],[
                'title' => '请输入标题',
                'cid' => '请选择分类',
                'content' => '请输入文章内容',
                'keywords' => '请输入关键字',
                'description' => '请输入描述',
            ]);

            // 接收数据
            $data['title'] = $request->input('title','','htmlspecialchars');
            $data['cid'] = $request->input('cid');
            $data['author'] = $request->input('author','','htmlspecialchars');
            $data['keywords'] = $request->input('keywords','','htmlspecialchars');
            $data['sort'] = $request->input('sort');
            $data['click'] = $request->input('click');
            $data['description'] = $request->input('description','','htmlspecialchars');
            $data['content'] = $request->input('content','内容为空','htmlspecialchars');
            # 数据更新
            $res = $this->article->where('aid',$aid)->update($data);
            if($res){
                Cache::flush();
                return redirect('/admin/article_list');
            } else {
                return redirect('/prompt')->with(['message'=>'修改失败','url' =>'/admin/article_edit/'.$aid, 'jumpTime'=>3,'status'=>'error']);
            }
        }

        return view('admin/article_edit',['category'=>$category,'article'=>$article,'cat'=>$cat]);
    }

	// 禁用列表
	public function article_status(Request $request)
	{
		if($request->isMethod('post')){
			$aid = $request->input('aid');
			$is_show = $request->input('is_show');
			if(!preg_match('/^[1-9]\d*$/',$aid)) json_return(1000,'参数错误');
			if(!preg_match('/^[0-1]\d*$/',$is_show)) json_return(1000,'参数错误');
			# 修改状态
			$res = DB::table('article')->where('aid',$aid)->update(['is_show'=>$is_show]);
			if($res){
                Cache::flush();
				json_return(200,'操作成功');
			} else {
				json_return(1000,'操作失败');
			}
		} else {
			json_return(1000,'非法操作');
		}
	}

	// 添加标签
    public function add_article_tag(Request $request)
    {
        if($request->isMethod('post')){
            $data = $request->all();
            # 首先判断标签库中是否存在该文章的标签
            $a_tag = DB::table('article_tag')->where('aid',$data['aid'])->select('aid','tid')->select();
            if(!empty($a_tag)){
                # 如果存在标签，则执行替换标签操作（将原有标签删除，增加新的标签）
                DB::table('article_tag')->where('aid',$data['aid'])->delete();
                foreach ($data['tid'] as $k => $v) {
                    DB::table('article_tag')->insert(['aid'=>$data['aid'],'tid'=>$v]);
                }
                return redirect('/prompt')->with(['message'=>'更换成功','url' =>'/admin/article_list', 'jumpTime'=>3,'status'=>'success']);
            }else{
                # 如果不存在，则新增文章标签
                foreach ($data['tid'] as $k => $v) {
                    DB::table('article_tag')->insert(['aid'=>$data['aid'],'tid'=>$v]);
                }
                return redirect('/prompt')->with(['message'=>'新增成功','url' =>'/admin/article_list', 'jumpTime'=>3,'status'=>'success']);
            }
        }

    }

    // 文章软删除
    public function article_del(Request $request)
    {
        $aid = $request->input('aid');
        if(!preg_match('/^[1-9]\d*$/',$aid)) json_return(1000,'参数错误');
        # 软删除
        $res = $this->article->where('aid',$aid)->update(['deleted_at'=>1]);
        if($res){
            Cache::flush();
            json_return(200,'删除成功');
        } else {
            json_return(1000,'删除失败');
        }
    }

    // 回收站
    public function article_recovery()
    {
        # 文章列表
        $article = $this->article->getPageData('all','all','all','*',1);
        return view('admin/article_recovery',['articles'=>$article]);
    }

    // 恢复文章
    public function recovery(Request $request)
    {
        $aid = $request->input('aid');
        if(!preg_match('/^[1-9]\d*$/',$aid)) json_return(1000,'参数错误');
        # 恢复
        $res = $this->article->where('aid',$aid)->update(['deleted_at'=>0]);
        if($res){
            Cache::flush();
            json_return(200,'恢复成功');
        } else {
            json_return(1000,'恢复失败');
        }
    }

    // 彻底删除文章
    public function del_all(Request $request)
    {
        $aid = $request->input('aid');
        if(!preg_match('/^[1-9]\d*$/',$aid)) json_return(1000,'参数错误');
        # 查询是否存在文章
        $aritcle = $this->article->find($aid);
        //查询图片路径
        $path    = DB::table('article_pic')->where('aid',$aid)->select('path')->first();
        if($aritcle && $aritcle->deleted_at == 1){
            # 删除文章、标签、封面
            $res = DB::table('article')->where('aid',$aid)->delete();
            if($res){
                DB::table('article_pic')->where('aid',$aid)->delete();
                DB::table('article_tag')->where('aid',$aid)->delete();
                unlink('.'.$path->path);
                json_return(200,'删除成功');
            } else {
                json_return(1000,'删除失败');
            }
        } else {
            json_return(1000,'文章不存在');
        }
    }
	
}
